import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");
        ExecutorService service = Executors.newCachedThreadPool();
        while(true)
        {
            //通过accept方法, 把内核中已经建立好的连接拿到应用程序中
            //建立连接的流程都是内核自动完成, 应用程序只需要"捡现成的"
            Socket clientSocket = serverSocket.accept();

//            Thread t = new Thread(() -> {
//                processConnection(clientSocket);
//            });
//            t.start();

            //更好一点的办法, 是使用线程池
            service.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }

    public void processConnection(Socket clientSocket)
    {
        //进入方法, 先打印一个日志, 表示当前有客户端连上了
        System.out.printf("[%s:%d] 客户端上线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
        //接下来进行数据的交互
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            while(true)
            {
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext())
                {
                    //连接断开了, 此时循环就应该结束了
                    System.out.printf("[%s:%d] 客户端下线了!\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //1. 读取请求并解析, 此处以next来作为读取请求的方式, next 的规则是读到空白符就返回
                String request = scanner.next();

                //2. 根据请求, 计算响应
                String response = process(request);

                //3. 把响应写回到客户端
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();

                //4. 打印请求交互的内容
                System.out.printf("[%s:%d] req=%s, resp=%s\n", clientSocket.getInetAddress(), clientSocket.getPort(), request, response);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            try{
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
